<?php
/**
 * @filesource modules/category/controllers/CategoryController.php
 * @author Dao Quang Duc
 */ 
Class Category_IndexController extends Clu_Controller_Action_Hvn
{
	public $m; //model

	public function init()
	{
		$this->m = new category_Model_Category();
		parent::init();
	}
 	  	
	public function moduleCategoryAction()
	{
       $sess = new Zend_Session_Namespace(CLU_NS);
        //check user rights
        if (strpos ($sess->userPermissions, 'administer everything') === false)
            {
                $this->view->errorMessage = t(68);
                $this->renderToHolder( 'common/error.phtml');
                return;
            }
                
		
		$this->view->successMessage = '';
		$this->view->errorMessage = '';
		if ($moduleCategoryName = $this->_request->getParam("module_category"))
	   	{
	   		$operation = $this->_request->getParam("operation");
	   		if ($operation == 'new') 
        		$sql = sprintf("CREATE TABLE `%s` (
          				`id` int(8) NOT NULL auto_increment,
          				`name` varchar(256) collate utf8_unicode_ci NOT NULL,
          				`description` text collate utf8_unicode_ci NOT NULL,
                          `tree_path` varchar(512) collate utf8_unicode_ci NOT NULL,
                          PRIMARY KEY  (`id`)
                        	) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
    
    					CREATE TABLE `%s` (
      					`id` int(8) NOT NULL,
      					`pid` int(8) NOT NULL,
                          PRIMARY KEY  (`id`,`pid`)
                        ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
                        ", 'categories_' . $moduleCategoryName, 'category_relations_' . $moduleCategoryName );
			else if ($operation == 'delete')
				$sql = sprintf(" DROP TABLE `%s`; DROP TABLE `%s`;", 'categories_' . $moduleCategoryName, 'category_relations_' . $moduleCategoryName );
    		try 
    		{
//    			die ($sql);
    			$this->db->query($sql);
    			$this->view->successMessage = $operation . __(" <i>categories_$moduleCategoryName </i> and <i>category_relations_$moduleCategoryName </i> successful");
    		}
			catch (Exception $e)    
			{
    			$this->view->errorMessage = __("Something wrong when ") .$operation."ing the table" . $e->getMessage();
			}
	   	}		
	   	$this->module_category = $moduleCategoryName;
		$this->renderToHolder("category/module-category-creation.phtml");
	}
	
	public function newAction()
	{	
		if(!$type = $this->_request->getParam('category_type'))
      	{
      		$this->renderToHolder('category/chooseNewCategory.phtml');
      		return;
      	}
        else
        {
        	if($type != 'general') {
        		$this->m->setTables($type);
        	}
        	$form = new category_Form_Category();
        	$form->cluBuild(array('type'=>$type));
        	
    		$this->view->form = $form;
    		$this->view->category_type = $type;
    		if ($this->_request->isPost() && $this->view->form->isValid($_POST)) 
    			if ($this->m->insertRaw($this->_request->getParams(), false))
            	{
                	$lastInsertId = $this->db->lastInsertId();
                    //forward to avoid refreshing
                    $this->_forward("success", 'index' , 'category', array('lastInsertId' => $lastInsertId, 'lang' => 'en' ) );
                    return;
            	}
            $this->renderToHolder('category/new.phtml');
        }
	}
	
	public function viewAction()
    {
    	
    	$categoryId = $this->_request->getParam("id");
    	$type = $this->_request->getParam("type");
        if($type != 'general') 
        		$this->m->setTables($type);

        if (!$c = $this->m->findByPrimary($categoryId))
        {
            $this->view->errorMessage = __('Cannot find the requested category');
            $this->renderToHolder('common/error.phtml');
            return;
        }
       	$this->view->category = $c;
       	$this->view->category_type = $type;
       	$this->renderToHolder( 'category/view.phtml');  
    }
    
    public function editAction()
    {
    	$id = $this->_request->getParam("id");
        $type = $this->_request->getParam("type");
        if($type != 'general') 
        		$this->m->setTables($type);
        		
    	if (!$c = $this->m->findByPrimary($id))
        {                
            $this->view->errorMessage = __('Cannot find the requested category');
            $this->renderToHolder('common/error.phtml');
            return;
        }
        
        //everything's fine. Continue editing
        $form = new category_Form_Category();
        $form->cluBuild(array('type'=>$type));
        
        $form->setAction('/en/category/index/edit');
        $form->submit->setLabel(__('Update'));
        
        //populate the data from DB
		if (!$this->_request->isPost())
		{
            $formData = $c->toArray();
    		$formData['pid'] = $this->m->findParentId($id);
			$form->populate($formData);
		}
		
        else if ($form->isValid($_POST))
        {
            if ($this->m->saveRaw($c, $form->getValues(), $id, false))
            {
                $this->view->operation = __("update category");
                $this->renderToHolder('common/success.phtml');
                return;
            }
            else 
                $this->view->errorMessage = __("Could not update category to DB");
        }
        else 
        	$this->view->errorMessage = __("Input is not valid");

        $this->view->form = $form;
        $this->view->id = $id;
        $this->view->category_type = $type;
        $this->renderToHolder('category/edit.phtml');    
    }

    public function deleteAction()
    {
    	if (!$id = $this->_request->getParam('id'))
    	{
    		$this->view->errorMessage = __('No article id specified');
    		$this->renderToHolder('common/error.phtml');
            return;
        }
        $type = $this->_request->getParam("type");
        if($type != 'general') 
        		$this->m->setTables($type);
        
        if ($this->m->updateTree($id, -1))
        {
            $this->view->operation = __("Delete category");
            $this->renderToHolder( 'common/success.phtml');
        }
		else
		{   
			$this->view->errorMessage = __('Could not delete from DB');
            $this->renderToHolder('common/error.phtml');
		}   
    }
    
	public function searchAction()
    {

      	if(!$type = $this->_request->getParam('category_type'))
      	{
      		$this->renderToHolder('category/chooseCategory.phtml');
      		return;
      	}
        else
        {
        	if($type != 'general') {
        		$this->m->setTables($type);
        	}
            //$form = new category_Form_Search();
            $form = new category_Form_Search();
        	$form->cluBuild(array('type'=>$type));
            
            //TODO: pass type to category_Form_Search so that mCategory can search 
            //the right table
            //wtf????
        	$this->view->form = $form; //die_a($form);
        	$this->view->category_type = $type;
			if($this->_request->isPost() && $form->isValid($_POST))
    	    	if($categoryList = $this->m->search($this->_request->getParams()))
        		{
      				$this->view->categoryList = $categoryList;//list of found categories
      				$this->category_type = $type;
    	            $this->renderToHolder('category/list.phtml',false, null, 4,2); 
            	}
            $this->renderToHolder('category/search.phtml',false, null, 4,1); //search box 
        }
    }
    
	public function successAction()
    {
         $this->view->categoryId =  $this->_request->getParam("lastInsertId");
         $this->renderToHolder( 'common/success.phtml');  
    }
}
?>
